local CellHelper = require("app.public.CellHelper")
local GoodsData = require("app.datacenter.GoodsData")
local TradeData = require("app.datacenter.TradeData")
local TradeItemDetail = require("app.layers.trade_TradeItemDetail")
local LongTouch = require("app.public.LongTouch")
local Alert = require("app.public.Alert")
local TradeUIStoreLayer=class("TradeUIStoreLayer",FZutil.createTransportUILayer)


local cell_big = {width = 90+10, height = 140+10}
local nums_big = 4				--一行有cell的个数
local space_big = 60

local cell_small = {width = 86+10, height = 86+10}
local nums_small = 6				--一行有cell的个数
local space_small = 60

local STORE_TYPE_PURCHASE = 101
local STORE_TYPE_SALE = 102

local PURCHASE_TYPE_FIXED = 201
local PURCHASE_TYPE_MAXINUM = 202

local TOUCH_DOWN_TIME = 1.2 --按下1.2秒触发拖拽机制
local PER_SCROLL_TIME = 0.5 --每0.5秒移动一次包裹

local function getPos(index,cell_sz)
	return space_big+cell_sz.width*((index-1)%nums_big),-cell_sz.height/2-cell_sz.height*math.floor((index-1)/nums_big)
end

local function getPos2(index,cell_sz)
	return space_small+cell_sz.width*((index-1)%nums_small),-cell_sz.height/2-cell_sz.height*math.floor((index-1)/nums_small)
end
--计算当前拖动到的格子号
local function getIndex2(pos,cell_sz,box_h)
    local col = math.floor( (pos.x-space_small+cell_sz.width/2)/cell_sz.width )
    local row = math.floor( (box_h-pos.y)/cell_sz.height )
    if col<0 or col>=nums_small or row<0 then--or row>XX
        return 0 
    end
    local index = row*nums_small+col+1
    print(row,col,index)
    return index
end

function TradeUIStoreLayer:ctor(storetype)
    self:enableNodeEvents()
	local uimap=FZutil.createSceneNode("TradeUIall/TradeStore")
	self.uimap=uimap
	self:addChild(uimap.root)
    uimap.root:setPosition(display.center)

    self.list_right = uimap.ScrollView_bag
    self.list_left = uimap.ScrollView_item

    self.storeType = storetype or STORE_TYPE_PURCHASE
    
    self.lastIndex = 0 --记录上个移动到的位置 马车背包

    --税率
    DyTradeStore:setGoodsType(GOOODS_TYPE_LOCAL)
    self:initStoreUI()
end
--初始化商店UI
function TradeUIStoreLayer:initStoreUI()  
    self.purchaseType = PURCHASE_TYPE_FIXED
    local uimap = self.uimap

    local Button_buy = uimap.Button_buy
    local Button_sale = uimap.Button_sale
    local Button_confirm = uimap.Button_confirm

    Button_buy:onTouch(function(e)
		if e.name == "began" then
			local rclitems = DyTransportPack:getRecycleItems()
            if table.maxn(rclitems) > 0 then
                Alert:show("",Language.trade.clear_recycleitems,Alert.TYPE_YES_NO,function(isY)
                    if isY then     --重新下载project.manifest
                        NetEngine:sendMessage(ProtoCmd.ReqSellGoodsMessage,self.settlemsg,true)
                    else
                        DyTransportPack:clearRecycleItems()
                    end
                    self:switchStore(true)
                end)
                return            
            end
            self:switchStore(true)			
		end
	end)
    Button_sale:onTouch(function(e)
		if e.name == "began" then
            local caritems = DyTransportPack:getCartItems()
            if table.maxn(caritems) > 0 then
                Alert:show("",Language.trade.clear_caritems,Alert.TYPE_YES_NO,function(isY)
                    DyTransportPack:clearCartItems()
                    if isY then
                        NetEngine:sendMessage(ProtoCmd.ReqBuyGoodsMessage,self.settlemsg,true)      
                    end
                    self:switchStore(true)
                end)
                return            
            end
			self:switchStore(true)
		end
	end)
    Button_confirm:onTouch(function(e)
		if e.name == "ended" then
            if self.storeType == STORE_TYPE_PURCHASE then   
                local caritems = DyTransportPack:getCartItems()
                if table.maxn(caritems) > 0 then       
			        NetEngine:sendMessage(ProtoCmd.ReqBuyGoodsMessage,self.settlemsg,true)
                else
                    Alert:show("",Language.trade.pls_choose_item,Alert.TYPE_YES)
                end
            else
                local rclitems = DyTransportPack:getRecycleItems()
                if table.maxn(rclitems) > 0 then       
			        NetEngine:sendMessage(ProtoCmd.ReqSellGoodsMessage,self.settlemsg,true)
                else
                    Alert:show("",Language.trade.pls_choose_item,Alert.TYPE_YES)
                end
            end
		end
	end)

    local CheckBox_0 = uimap.CheckBox_0
    local CheckBox_1 = uimap.CheckBox_1
    local CheckBox_2 = uimap.CheckBox_2
    local CheckBox_3 = uimap.CheckBox_3
    CheckBox_1:setSelected(true)
    CheckBox_2:setSelected(false)
    CheckBox_3:setSelected(false)

    CheckBox_0:onEvent(function(event)
        if event.name == "unselected" then
            event.target:setSelected(true)
        end
    end)
    CheckBox_1:onEvent(function(event)
        if event.name == "selected" then
            DyTradeStore:setGoodsType(GOOODS_TYPE_LOCAL)
            CheckBox_2:setSelected(false)         
            CheckBox_3:setSelected(false)
            self:updateInfo(true,true)
        elseif event.name == "unselected" then
            event.target:setSelected(true)
        end
    end)
    CheckBox_2:onEvent(function(event)
        if event.name == "selected" then
            DyTradeStore:setGoodsType(GOOODS_TYPE_LIVE)
            CheckBox_1:setSelected(false)         
            CheckBox_3:setSelected(false)
            self:updateInfo(true,true)
        elseif event.name == "unselected" then
            event.target:setSelected(true)
        end
    end)
    CheckBox_3:onEvent(function(event)
        if event.name == "selected" then
            DyTradeStore:setGoodsType(GOOODS_TYPE_EMERGENCY)
            CheckBox_1:setSelected(false)         
            CheckBox_2:setSelected(false)
        elseif event.name == "unselected" then
            event.target:setSelected(true)
        end
    end)

    local CheckBox_fixed = uimap.CheckBox_fixed
    local CheckBox_max = uimap.CheckBox_max
    CheckBox_fixed:setSelected(self.purchaseType == PURCHASE_TYPE_FIXED)
    CheckBox_fixed:onEvent(function(event)
        if event.name == "selected" then
            self.purchaseType = PURCHASE_TYPE_FIXED
            CheckBox_max:setSelected(false)         
        elseif event.name == "unselected" then
            event.target:setSelected(true)
        end
    end)
    CheckBox_max:setSelected(self.purchaseType == PURCHASE_TYPE_MAXINUM)
    CheckBox_max:onEvent(function(event)
        if event.name == "selected" then
            self.purchaseType = PURCHASE_TYPE_MAXINUM
            CheckBox_fixed:setSelected(false)         
        elseif event.name == "unselected" then
            event.target:setSelected(true)
        end
    end)

    self:switchStore()
end
--切换商店类型
function TradeUIStoreLayer:switchStore(switch)
    if switch and self.storeType == STORE_TYPE_PURCHASE then
        self.storeType = STORE_TYPE_SALE
    elseif switch then
        self.storeType = STORE_TYPE_PURCHASE
    end
    local Button_buy = self.uimap.Button_buy
    local Button_sale = self.uimap.Button_sale
    Button_buy:setTouchEnabled(self.storeType ~= STORE_TYPE_PURCHASE)
    Button_buy:setBright(self.storeType ~= STORE_TYPE_PURCHASE)
    Button_sale:setTouchEnabled(self.storeType ~= STORE_TYPE_SALE)
    Button_sale:setBright(self.storeType ~= STORE_TYPE_SALE)
    --标签页隐藏
    if self.storeType==STORE_TYPE_PURCHASE then
        self.uimap.CheckBox_0:setVisible(false)
        self.uimap.CheckBox_1:setVisible(true)
        self.uimap.CheckBox_2:setVisible(true)
        self.uimap.CheckBox_3:setVisible(true)
    elseif self.storeType == STORE_TYPE_SALE then
        self.uimap.CheckBox_0:setVisible(true)
        self.uimap.CheckBox_1:setVisible(false)
        self.uimap.CheckBox_2:setVisible(false)
        self.uimap.CheckBox_3:setVisible(false)
    end

    self:updateInfo(true)
end

function TradeUIStoreLayer:scheduleUpdate()
	if not self.schedulerEntry then
		self.schedulerEntry = cc.Director:getInstance():getScheduler():scheduleScriptFunc(handler(self, self.Update), 0, false)
	end
end

function TradeUIStoreLayer:unscheduleUpdate()
	if self.schedulerEntry then
		cc.Director:getInstance():getScheduler():unscheduleScriptEntry(self.schedulerEntry)
		self.schedulerEntry = nil
	end
end

function TradeUIStoreLayer:Update()
	if not self.schedulerEntry then return end
	if self.storeType == STORE_TYPE_PURCHASE then
        local itemsL= DyTradeStore:getStoreList()
        local itemsR= DyTransportPack:getPacks()
        if self.loading_pos_l >= #itemsL and self.loading_pos_r >= #itemsR then
            self:unscheduleUpdate()
            return
        end
		self:loadBuylistL()
        self:loadBuylistR()
	else
        local itemsL= DyTransportPack:getPacks()
        local itemsR= DyTransportPack:getRecycleItems()
        if self.loading_pos_l >= #itemsL and self.loading_pos_r >= #itemsR then
            self:unscheduleUpdate()
            return
        end
		self:loadSelllistL()
        self:loadSelllistR()
	end
end

function TradeUIStoreLayer:loadBuylistL()
    local items = DyTradeStore:getStoreList()
    if self.loading_pos_l >= #items then 
		return
	end
	local size = self.list_left:getInnerContainerSize()
	local item = items[self.loading_pos_l+1]
    
    local cell = FZutil.createCellNode("TradeUIall/TradeNodeBig")
    local cellmap = CellHelper.initWithNode(cell.FileNode_small)
    CellHelper.setCellData(cellmap,item.id,Cell_Type.STORE,item:getCount())
    cell.Text_name:setString(configData.cfg_items[item.id].name)
    cell.Text_price_N:setString(Utils.getCoinStrByQuality(item:getQuality())..item:getBuyPrice(RoleData.player_info.stageid,1))
    
	self.list_left:addChild(cell.root)
    table.insert(self.cellsL,cell)
    local posx,posy = getPos(self.loading_pos_l+1,cell_big)
	posy = posy+self.list_left_h
	cell.root:setPosition(posx,posy)  

    local function longPressFunc(sender,event)
        if event == "longPressBegin" then
            local tradeItemDetailLayer = TradeItemDetail.new()
            tradeItemDetailLayer:setItemInfo(TradeItemDetail.shopItems,item.id,item.count)
            self:addChild(tradeItemDetailLayer)
        end
    end

    local function clickfunc()
        if self.purchaseType == PURCHASE_TYPE_FIXED then
            local tradeItemDetailLayer = TradeItemDetail.new()
            tradeItemDetailLayer:setItemInfo(TradeItemDetail.shopItems,item.id,item.count)
            self:addChild(tradeItemDetailLayer)
        else
            if item.itemtype==2 then 
                --道具
                self:purchaseGoods(item.id,item.overlying)
            else
                self:purchaseGoods(item.id,item.count)
            end
            FzEventCenter:DispichEvent(FzEvent.UpdateTradeingInfo)
        end
    end
    
    LongTouch.registerLongPressHandler(cell.Image_icon,longPressFunc,clickfunc,0.65)    

    self.loading_pos_l = self.loading_pos_l + 1
end

--刷新左边的商店
function TradeUIStoreLayer:updateBuylistL()
    local items = DyTradeStore:getStoreList()
    
    for _index,item in pairs(items) do
        local cell = self.cellsL[_index]
        CellHelper.setCellData(cell.FileNode_small,item.id,Cell_Type.STORE,item:getCount())
        cell.Text_name:setString(configData.cfg_items[item.id].name)
        cell.Text_price_N:setString(Utils.getCoinStrByQuality(item:getQuality())..item:getBuyPrice(RoleData.player_info.stageid,1))
	end  
end

--逐个载入背包列表
function TradeUIStoreLayer:loadBuylistR()
    local items = DyTransportPack:getPacks()
    if self.loading_pos_r >= #items then 
		return
	end
	local size = self.list_right:getInnerContainerSize()
	local item = items[self.loading_pos_r+1]
	if item then
        local cell = CellHelper.createOneCell()
        if item.gdata then
            CellHelper.setCellData(cell,item.gdata.id,Cell_Type.TPACK,item.gdata:getCount())
            CellHelper.setGray(cell,item.isown)
        else
            CellHelper.setdata(cell,nil)
        end       
        cell.root:setTag(self.loading_pos_r+1)
		self.list_right:addChild(cell.root)
        table.insert(self.cellsR,cell)
        local posx,posy = getPos2(self.loading_pos_r+1,cell_small)
		posy = posy+self.list_right_h
		cell.root:setPosition(posx,posy)  

        cell.Image_icon:onTouch(function(e)
            if e.name == "began" then
                self.curcell = cell.root
                self.touchBeganTime = 0
                self:startUpdateTouchBegan()
            elseif e.name == "moved" then
                if self.touchBeganTime < TOUCH_DOWN_TIME then
                    return
                end
                self.list_right:setTouchEnabled(false)
                self.packTouchPoint = e.target:getTouchMovePosition()
                cell.root:setPosition(self:getCellToBagPos(self.packTouchPoint))
                cell.root:setLocalZOrder(1000)
                local innerp = self.list_right:convertToNodeSpace(e.target:getTouchMovePosition())
                --到达边界
                if innerp.y <= 10 or innerp.y >= 310-10 then
                    if self:checkUpdateBagScroll() then
                        self.bagScrollDuration = PER_SCROLL_TIME               
                        self:startUpdateBagScroll()
                    end
                else
                    self:stopUpdateBagScroll()
                end
                self:doCellDrag(cell.root)
			elseif e.name == "ended" then
                self:stopUpdateTouchBegan()
                self:stopUpdateBagScroll()
                self.list_right:setTouchEnabled(true)               
                --移动的物品不响应事件
                if self.touchBeganTime >= TOUCH_DOWN_TIME then
                    self:doCellDrag(cell.root,true)
                    return
                end
                if self.storeType== STORE_TYPE_PURCHASE and item.isown then
                    return
                end
                if PURCHASE_TYPE_FIXED == self.purchaseType then
                    local tradeItemDetailLayer = TradeItemDetail.new()
                    tradeItemDetailLayer:setItemInfo(TradeItemDetail.packBuyItems,item.index,item.gdata:getCount())
                    self:addChild(tradeItemDetailLayer)
                else
                    DyTransportPack:undoPurchase(item.index,item.gdata:getCount())
                    FzEventCenter:DispichEvent(FzEvent.UpdateTradeingInfo)
                end
            else
                self:stopUpdateTouchBegan()
                self:stopUpdateBagScroll()
                self.list_right:setTouchEnabled(true)              
                if self.touchBeganTime >= TOUCH_DOWN_TIME then
                    self:doCellDrag(cell.root,true)
                    return
                end
			end
		end)
	end
	self.loading_pos_r = self.loading_pos_r + 1
end

--更新右边
function TradeUIStoreLayer:updateBuylistR(cleanup)
    --背包列表
    local items = DyTransportPack:getPacks()
    for _index,item in pairs(items) do
        local cell = nil
        if self.cellsR[_index] then
            cell = self.cellsR[_index]
            cell.root:setLocalZOrder(0)
            if item.gdata then
                cell.root:setLocalZOrder(0)
                CellHelper.setGray(cell,false)
                CellHelper.setCellData(cell,item.gdata.id,Cell_Type.TPACK,item.gdata:getCount())
                CellHelper.setGray(cell,item.isown)
            else
                CellHelper.setdata(cell,nil)
            end  
            --拖拽结束调整位置
            local posx,posy = getPos2(_index,cell_small)
		    posy = posy+self.list_right_h
		    cell.root:setPosition(posx,posy)  
        end        
	end
end

function TradeUIStoreLayer:loadSelllistL()
    local items = DyTransportPack:getPacks()
    if self.loading_pos_l >= #items then 
		return
	end
	local item = items[self.loading_pos_l+1]
	if item then
        local cell = FZutil.createCellNode("TradeUIall/TradeNodeBig")
        local cellmap = CellHelper.initWithNode(cell.FileNode_small)
        if item.gdata then
            CellHelper.setCellData(cellmap,item.gdata.id,Cell_Type.TPACKS,item.gdata:getCount())
            cell.Text_name:setString(configData.cfg_items[item.gdata.id].name)
            cell.Text_price_N:setString(Utils.getCoinStrByQuality(item.gdata:getQuality())..item.gdata:getSellPrice(RoleData.player_info.stageid,1))
        else
            CellHelper.setdata(cellmap,nil)
            cell.Text_name:setString("")
            cell.Text_price_N:setString("")
            cellmap.Text_name:hide()
            cellmap.Image_frame:hide()
        end
                     
		self.list_left:addChild(cell.root)
        table.insert(self.cellsL,cell)
        local posx,posy = getPos(self.loading_pos_l+1,cell_big)
		posy = posy+self.list_left_h
		cell.root:setPosition(posx,posy)

        local function longPressFunc(sender,event)
            if event == "longPressBegin" then
                local tradeItemDetailLayer = TradeItemDetail.new()
                tradeItemDetailLayer:setItemInfo(TradeItemDetail.packSellItems,item.index,item.gdata:getCount())
                self:addChild(tradeItemDetailLayer)
            end
        end

        local function clickfunc()
            if self.purchaseType == PURCHASE_TYPE_FIXED then
                local tradeItemDetailLayer = TradeItemDetail.new()
                tradeItemDetailLayer:setItemInfo(TradeItemDetail.packSellItems,item.index,item.gdata:getCount())
                self:addChild(tradeItemDetailLayer)
            else
                DyTransportPack:sellGoods(item.index,item.gdata:getCount())
                FzEventCenter:DispichEvent(FzEvent.UpdateTradeingInfo)
            end
        end
    
        LongTouch.registerLongPressHandler(cell.Image_icon,longPressFunc,clickfunc,0.65)   
    end

    self.loading_pos_l = self.loading_pos_l + 1
end

--刷新左边的马车背包
function TradeUIStoreLayer:updateSelllistL()
    local items = DyTransportPack:getPacks()
    
    for _index,item in pairs(items) do
		local cell = nil
        if self.cellsL[_index] then
            cell = self.cellsL[_index]
            local cellmap = cell.FileNode_small
            if item.gdata then
                CellHelper.setCellData(cellmap,item.gdata.id,Cell_Type.TPACKS,item.gdata:getCount())
                cell.Text_name:setString(configData.cfg_items[item.gdata.id].name)
                cell.Text_price_N:setString(Utils.getCoinStrByQuality(item.gdata:getQuality())..item.gdata:getSellPrice(RoleData.player_info.stageid,1))
            else
                CellHelper.setdata(cellmap,nil)
                cell.Text_name:setString("")
                cell.Text_price_N:setString("")
                cellmap.Text_name:hide()
                cellmap.Image_frame:hide()
            end
        end
	end  
end

function TradeUIStoreLayer:loadSelllistR()
    local items = DyTransportPack:getRecycleItems()
    if self.loading_pos_r >= #items then 
		return
	end
	local item = items[self.loading_pos_r+1]

    local cell = self:createOneRecycleCell(self.loading_pos_r+1)   
    cell.root:setTag(self.loading_pos_r+1)
	self.list_right:addChild(cell.root)
    table.insert(self.cellsR,cell)
    local posx,posy = getPos2(self.loading_pos_r+1,cell_small)
	posy = posy+self.list_right_h
	cell.root:setPosition(posx,posy)
        
    CellHelper.setCellData(cell,item.id,Cell_Type.RECYCLE,item.totalcount)    

    self.loading_pos_r = self.loading_pos_r+1
end

function TradeUIStoreLayer:createOneRecycleCell(index)
    local cell = CellHelper.createOneCell()
    
    local function longPressFunc(sender,event)
        if event == "longPressBegin" then
            local items = DyTransportPack:getRecycleItems()
	        local item = items[index]
            local tradeItemDetailLayer = TradeItemDetail.new()
            tradeItemDetailLayer:setItemInfo(TradeItemDetail.recycleItems,item.id,item.totalcount)
            self:addChild(tradeItemDetailLayer)
        end
    end

    local function clickfunc()
        local items = DyTransportPack:getRecycleItems()
	    local item = items[index]
        if PURCHASE_TYPE_FIXED == self.purchaseType then
            local tradeItemDetailLayer = TradeItemDetail.new()
            tradeItemDetailLayer:setItemInfo(TradeItemDetail.recycleItems,item.id,item.totalcount)
            self:addChild(tradeItemDetailLayer)
        else
            DyTransportPack:undoSell(item.id,item.totalcount)
            FzEventCenter:DispichEvent(FzEvent.UpdateTradeingInfo)
        end
    end
    
    LongTouch.registerLongPressHandler(cell.Image_icon,longPressFunc,clickfunc,0.65)   

    return cell
end

--更新右边  回收仓库
function TradeUIStoreLayer:updateSelllistR()
    local items = DyTransportPack:getRecycleItems()
    for i=1,math.max(#self.cellsR,#items) do
        local cell = self.cellsR[i]
        local item = items[i]
        if cell and item then
            CellHelper.setCellData(cell,item.id,Cell_Type.RECYCLE,item.totalcount)
        elseif cell then
            cell.root:removeFromParent()
            self.cellsR[i]=nil
        elseif item then
            cell = self:createOneRecycleCell(i)   
            cell.root:setTag(i)
	        self.list_right:addChild(cell.root)
            table.insert(self.cellsR,cell)
            local posx,posy = getPos2(i,cell_small)
	        posy = posy+self.list_right_h
	        cell.root:setPosition(posx,posy)
            CellHelper.setCellData(cell,item.id,Cell_Type.RECYCLE,item.totalcount)
        end
        
	end
end

--从背包拿出物品
function TradeUIStoreLayer:takeOutGoods(index,goodsData)
    if self.storeType==STORE_TYPE_PURCHASE then
        for k,v in pairs(self.storeSaleList) do
            if v.id == goodsData.id and v.count~=-1 then
                v.count = v.count + goodsData.count
                break
            end
        end    
    else
        local isInSaleList = false
        for k,v in pairs(self.storeSaleList) do
            if v.id == goodsData.id and v.count~=-1 then
                v.count = v.count + goodsData.count
                isInSaleList = true
                break
            end
        end
        if not isInSaleList then
            table.insert(self.storeSaleList,goodsData)
        end
    end
end
--从背包拿出物品
function TradeUIStoreLayer:purchaseGoods(id,count)
    if DyTransportPack:purchaseGoods(id,count) == false then
        Alert:show("",Language.trade.full_pack2,Alert.TYPE_YES)
    end
end
function TradeUIStoreLayer:updateTradingInfo()
    self:updateInfo()
end

function TradeUIStoreLayer:reloadTradingInfo()
    self:updateInfo(true)
end


--结算信息
function TradeUIStoreLayer:updateSettlement(args)
    local Text_cost = self.uimap.Text_cost
    local Text_discount = self.uimap.Text_discount
    local Text_totalcost = self.uimap.Text_totalcost
    local cost = 0
    local totalcost = 0
    if self.storeType == STORE_TYPE_PURCHASE then
        cost,totalcost = self:calculateCartItem()
    else
        cost,totalcost = self:calculateRecycleItems()
    end   
    self.uimap.Text_total_gold:setString(RoleData.player_info.gold)
    self.uimap.Text_total_diamond:setString(RoleData.player_info.diamond)
    self.uimap.Text_cost_gold:setString(cost.gold)
    self.uimap.Text_cost_diamond:setString(cost.diamond)
    self.uimap.Text_discount:setString(DyTradeStore:getTax(1)..","..DyTradeStore:getTax(2)..","..DyTradeStore:getTax(3))
    self.uimap.Text_totalcost_gold:setString(totalcost.gold)
    self.uimap.Text_totalcost_diamond:setString(totalcost.diamond)
end
--计算 卖给商店的货物
function TradeUIStoreLayer:calculateRecycleItems()
    local items = DyTransportPack:getRecycleItems()
    local finalcost = {gold=0,diamond=0}
    local finaltcost = {gold=0,diamond=0}
    self.settlemsg = {items={}}
    for k,recycleitem in pairs(items) do
        local id = recycleitem.id
        local quality = configData.cfg_items[id].quality
        for idx,item in pairs(recycleitem.items) do
            local msg = {}
            msg.idx = item.idx
            msg.itemid = id
            msg.num = item.count
            table.insert(self.settlemsg.items,msg)

            local goodsdata = GoodsData.new(id,item.count)
            local price = goodsdata:getSellPrice(RoleData.player_info.stageid,item.count)
            local tax = math.floor(price*DyTradeStore:getTax(quality)/100)
            price = math.floor(price)
            if quality == 1 then
                finalcost.gold = finalcost.gold + price
                finaltcost.gold = finaltcost.gold + price - tax
            else
                finalcost.diamond = finalcost.diamond + price
                finaltcost.diamond = finaltcost.diamond + price - tax
            end
        end       
    end
    return finalcost,finaltcost
end
--计算买入时 购物车的货物
function TradeUIStoreLayer:calculateCartItem()
    local items = DyTransportPack:getCartItems()
    local finalcost = {gold=0,diamond=0}
    local finaltcost = {gold=0,diamond=0}
    self.settlemsg = {items={}}
    for k,cartitem in pairs(items) do
        local item = cartitem.gdata
        local price = item:getBuyPrice(RoleData.player_info.stageid,item.count)
        local tax = math.floor(price*DyTradeStore:getTax(item:getQuality())/100)
        price = math.floor(price)
        if item:getQuality() == 1 then
            finalcost.gold = finalcost.gold + price
            finaltcost.gold = finaltcost.gold + price + tax
        else
            finalcost.diamond = finalcost.diamond + price
            finaltcost.diamond = finaltcost.diamond + price + tax
        end
        local msg = {}
        msg.idx = cartitem.index
        msg.itemid = item.id
        msg.num = item.count
        table.insert(self.settlemsg.items,msg)
    end
    return finalcost,finaltcost
end

function TradeUIStoreLayer:updateInfo(cleanup,leftupdate)
    --逐个载入列表单元
    local function loadlist(itemsL,itemsR)
        self.list_left:removeAllChildren()
        self.cellsL = {}
        self.loading_pos_l = 0
	    local box_h = cell_big.height*(math.ceil(table.maxn(itemsL)/nums_big))
        self.list_left_h = box_h<455 and 455 or box_h
        self.list_left:setInnerContainerSize(cc.size(455,self.list_left_h))

        if not leftupdate then
            self.list_right:removeAllChildren()
            self.cellsR = {}
            self.loading_pos_r = 0
	        local box_h = cell_small.height*(math.ceil(table.maxn(itemsR)/nums_small))
            self.list_right_h = box_h<310 and 310 or box_h
            self.list_right:setInnerContainerSize(cc.size(620,self.list_right_h))
        end

        self:scheduleUpdate()
    end
    if self.storeType == STORE_TYPE_PURCHASE then
        if cleanup then
            loadlist(DyTradeStore:getStoreList(),DyTransportPack:getPacks())
        else
            self:updateBuylistL()
            self:updateBuylistR()
        end
    else
        if cleanup then
            loadlist(DyTransportPack:getPacks(),DyTransportPack:getRecycleItems())
        else
            self:updateSelllistL()
            self:updateSelllistR()
        end
        
    end
    self:updateSettlement()
end

function TradeUIStoreLayer:updateBagScroll(dt)
    self.bagScrollDuration = self.bagScrollDuration + dt
    --1秒移动一次
    if self.bagScrollDuration>=PER_SCROLL_TIME then
        self.bagScrollDuration = 0
        local box_h = self.list_right:getInnerContainerSize().height
        local cell = self.curcell
        local h = cell:getPositionY()
        local percent = (1-h/box_h)*100
        local row = math.ceil(#self.cellsR/nums_small)
        local eachPer = 1/row*100
        local finalPer = eachPer*math.ceil(percent/eachPer)
        if percent<eachPer then
            finalPer = 0 
        end
        finalPer = finalPer<0 and 0 or finalPer
        finalPer = finalPer>100 and 100 or finalPer
        print(finalPer,percent,h)
        self.list_right:jumpToPercentVertical(finalPer)

        cell:setPosition(self:getCellToBagPos(self.packTouchPoint))
    end
end
--转换为背包中的坐标
function TradeUIStoreLayer:getCellToBagPos(touchpos)
    local innercp = self.list_right:getInnerContainerPosition()
    local innerp = self.list_right:convertToNodeSpace(touchpos)
    local movep = cc.pSub(innerp,innercp)
    return movep
end
--处理拖拽
function TradeUIStoreLayer:doCellDrag(cell,doswitch)
    local index = getIndex2(cc.p(cell:getPosition()),cell_small,self.list_right_h)
    if self.lastIndex~= index then
        local tar_cell = self.cellsR[index]
        local last_cell = self.cellsR[self.lastIndex]
        if tar_cell then
            tar_cell.Image_select:show()
        end
        if last_cell then
            last_cell.Image_select:hide()
        end
        self.lastIndex = index
   
    end
    if doswitch then
        if cell:getTag()~=index  then
            --DyTransportPack:doPackDrag(cell:getTag(),index)
            DyTransportPack:setDragState(true)
            NetEngine:sendMessage(ProtoCmd.ReqSwapMessage,{bType=2,fromIdx=cell:getTag(),toIdx=index},false)
        end
        --self:updateBuylistR()
    end     
end

function TradeUIStoreLayer:checkUpdateBagScroll()
    return self.scheduleUpdateBagScroll==nil
end

function TradeUIStoreLayer:updateTouchBegan(dt)
    self.touchBeganTime = self.touchBeganTime + dt
    if self.touchBeganTime > 1.2 then
        local cell = self.curcell
        cell.Image_select:setVisible(true)
        self:stopUpdateTouchBegan()
    end
end

-- 开启更新touchbegan
function TradeUIStoreLayer:startUpdateTouchBegan()
    self:stopUpdateTouchBegan()
    if not self.scheduleUpdateTouchBegan then
		self.scheduleUpdateTouchBegan = cc.Director:getInstance():getScheduler():scheduleScriptFunc(handler(self, self.updateTouchBegan), 1/10, false)
	end
end
-- 关闭更新touchbegan
function TradeUIStoreLayer:stopUpdateTouchBegan()
    if self.scheduleUpdateTouchBegan then
		cc.Director:getInstance():getScheduler():unscheduleScriptEntry(self.scheduleUpdateTouchBegan)
		self.scheduleUpdateTouchBegan = nil
	end
end

-- 开启更新列表滚动
function TradeUIStoreLayer:startUpdateBagScroll()
    self:stopUpdateBagScroll()
    if not self.scheduleUpdateBagScroll then
		self.scheduleUpdateBagScroll = cc.Director:getInstance():getScheduler():scheduleScriptFunc(handler(self, self.updateBagScroll), 1/10, false)
	end
end

-- 关闭更新列表滚动
function TradeUIStoreLayer:stopUpdateBagScroll()
    if self.scheduleUpdateBagScroll then
		cc.Director:getInstance():getScheduler():unscheduleScriptEntry(self.scheduleUpdateBagScroll)
		self.scheduleUpdateBagScroll = nil
	end
end


function TradeUIStoreLayer:onEnter()
    FzEventCenter:RegisterEvent(FzEvent.UpdateTradeingInfo, self, self.updateTradingInfo)
    FzEventCenter:RegisterEvent(FzEvent.ReloadTradeingInfo, self, self.reloadTradingInfo)
end

function TradeUIStoreLayer:onExit()
    FzEventCenter:RemoveEvent(FzEvent.UpdateTradeingInfo, self)
    FzEventCenter:RemoveEvent(FzEvent.ReloadTradeingInfo, self)
end

return TradeUIStoreLayer